export default function (method, url, data, sync = true) {
    method = method.toLowerCase();
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    if (xhr.status == 401) {
                        alert('未登录或登录超时\n重新登录');
                        top.location.assign('login.html');
                    } else {
                        alert('服务器忙，请稍后再试');
                    }
                    reject({
                        code: xhr.status,
                    })
                }
            }
        }

        if (method == 'get' && data) {
            let arr = [];
            for (let item in data) {
                arr.push(item + '=' + encodeURIComponent(data[item]));
            }
            url += '?' + arr.join('&');
        }

        xhr.open(method, url, true);

        const token = localStorage.getItem('token');
        if (token) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        }

        if (method == 'post') {
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(JSON.stringify(data));
        } else {
            xhr.send();
        }
    })
}